package csc.training.jsf2.view;

/**
 * Used as upload file bean
 * @author hdang20
 *
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

@ManagedBean
@RequestScoped
public class UploadFileBean {

    private UploadedFile uploadedFile;

    public void submit() throws IOException {
        String fileName = FilenameUtils.getName(uploadedFile.getName());
        String contentType = uploadedFile.getContentType();
        byte[] bytes = uploadedFile.getBytes();

        HttpServletRequest request  = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        
        String filePath = request.getContextPath() + "/uploadFolder" ;
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		
		File fileUpload = new File(filePath, fileName);
		FileOutputStream out = new FileOutputStream(fileUpload);
		out.write(bytes);
		out.flush();
		out.close();
		
        FacesContext.getCurrentInstance().addMessage(null, 
            new FacesMessage(String.format("File '%s' of type '%s' successfully uploaded!", fileUpload.getAbsolutePath(), contentType)));
    }

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

}
